import torch
from torch import nn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("D:\learn\深度学习\day53_pytorch入门(二)\代码\dataset\credit-a.csv", header=None)
print(data)

X = data.iloc[:, :-1]
Y = data.iloc[:, -1]
Y = Y.replace(-1, 0)

X = torch.from_numpy(X.values).type(torch.float32)
Y = torch.from_numpy(Y.values.reshape(-1, 1)).type(torch.float32)

model = nn.Sequential(
    nn.Linear(15, 1),
    nn.Sigmoid()
)

loss_fn = nn.BCELoss()
opt = torch.optim.SGD(model.parameters(), lr=0.0001)

batch_size = 32
steps = 653 // 32

for epoch in range(1000):
    for batch in range(steps):
        start = batch * batch_size
        end = start + batch_size
        x = X[start:end]
        y = Y[start:end]
        y_pred = model(x)
        loss = loss_fn(y_pred, y)
        opt.zero_grad()
        loss.backward()
        opt.step()

res = ((model(X).data.numpy() > 0.6) == Y.numpy()).mean()
print(res)